package cn.ccew.common.utils;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.type.Type;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.SequenceGenerator;

public class AssignedSequenceGenerator extends SequenceGenerator implements PersistentIdentifierGenerator, Configurable {
	private String entityName;

	public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
		entityName = params.getProperty(ENTITY_NAME);
		if (entityName == null) {
			throw new MappingException("no entity name");
		}

		super.configure(type, params, dialect);
	}

	public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
		Serializable id = null;
		try {
			id = JdbcUtils.getId();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (id == null) {
			id = super.generate(session, obj);
		}

		return id;
	}
}